

#include <mtx_util.h>

extern char comp_readable;
extern char new_file;
extern char *new_file_name;

int _do_add_sub_matrices(vm_matrix **mtx_array, int len, char op){

  if (len < 1){
    fprintf(stderr, "len < 1; actual len: %d\n", len);
    return 0;
  }

  vm_matrix *result;

  if (op == OP_ADD)
    result = vm_matrix_add(mtx_array[0], mtx_array[1]);
  else if (op == OP_SUB)
    result = vm_matrix_sub(mtx_array[0], mtx_array[1]);
  else {
    fprintf(stderr, "Unknown OP number: %d\n", op);
    return 0;
  }

  if (result == NULL){
    fprintf(stderr, "Error adding/subtracting the first two matrices.\n");
    return 0;
  }
  int i = 2;
  
  for ( ; i <= len; i++){
    vm_matrix *old = result;
    if (op == OP_ADD)
      result = vm_matrix_add(mtx_array[i], result);
    else if (op == OP_SUB)
      result = vm_matrix_sub(mtx_array[i], result);
    vm_free_matrix(old);
  }

  printf("Addition Resultant Matrix:\n");
  vm_print_matrix(result, "  ");

  if (new_file){
    FILE *nf = fopen(new_file_name, "w");
    if (nf == NULL){
      perror("Could not open new file");
      return 0;
    }
    if (comp_readable){
      vm_fprint_cr_matrix(nf, result);
    } else {
      vm_fprint_matrix(nf, result, " ");
    }
  } else {
    printf("Addition Resultant Matrix:\n");
    vm_print_matrix(result, "  ");
  }
  vm_free_matrix(result);

  return 1;

}

int add_matrices(vm_matrix **mtx_array, int len){

  return _do_add_sub_matrices(mtx_array, len, OP_ADD);

}

int sub_matrices(vm_matrix **mtx_array, int len){

  return _do_add_sub_matrices(mtx_array, len, OP_SUB);

}
